package com.game.config.netty.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Slf4j
@Component
public class MessageServerHandler extends SimpleChannelInboundHandler<String> {
    @Resource
    private ActionScanner actionScanner;
    @Resource
    private ApplicationContext applicationContext;
    @Resource
    private MessageService messageService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String json){
        log.info("{}",json);
        // Object bean = actionScanner.scan(json);
        String playerId = ctx.channel().remoteAddress().toString(); // 示例中使用远程地址作为玩家ID
        Object bean1 = applicationContext.getBean("pvpCityAction");
        log.info("{}",bean1);
        messageService.sendMessage(playerId, String.valueOf(bean1));
        // System.err.println(bean);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String playerId = ctx.channel().remoteAddress().toString(); // 示例中使用远程地址作为玩家ID
        messageService.subscribeToMessages(playerId, ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String playerId = ctx.channel().remoteAddress().toString(); // 示例中使用远程地址作为玩家ID
        messageService.unsubscribeFromMessages(playerId);
    }

    @Bean
    public void behaviorExecutor() {
    }
}
